<template>
  <view class="container">
    <scroll-view class="activity-list" scroll-y>
      <view v-for="item in activityList" :key="item.id" class="activity-card">
        <image :src="item.image_url" mode="aspectFill" class="activity-image"/>
        <view class="activity-info">
          <text class="activity-title">{{ item.title }}</text>
          <text class="activity-time">{{ formatTime(item.activity_start_time) }} - {{ formatTime(item.activity_end_time) }}</text>
          <text class="activity-location">{{ item.location }}</text>
          <text class="activity-points">{{ item.points }}积分</text>
          <text class="activity-status" :class="getStatusClass(item.status_text)">{{ item.status_text }}</text>
        </view>
        <view class="activity-actions">
          <button v-if="item.status === 1 && isActivityOngoing(item.activity_start_time, item.activity_end_time)" class="action-btn checkin-btn" @click="handleCheckin(item)">扫码签到</button>
          <button v-if="item.status === 1 && canCancel(item.activity_start_time)" class="action-btn cancel-btn" @click="handleCancel(item)">取消报名</button>
        </view>
      </view>
      <view v-if="activityList.length === 0" class="no-activity">暂无报名活动</view>
    </scroll-view>
  </view>
</template>

<script lang="ts" setup>
import { ref, onMounted } from 'vue';
import { request } from '../../utiles/request';

const activityList = ref<any[]>([]);

const formatTime = (time: string) => {
  if (!time) return '';
  const date = new Date(time.replace(/-/g, '/'));
  const y = date.getFullYear();
  const m = String(date.getMonth() + 1).padStart(2, '0');
  const d = String(date.getDate()).padStart(2, '0');
  const h = String(date.getHours()).padStart(2, '0');
  const min = String(date.getMinutes()).padStart(2, '0');
  return `${y}-${m}-${d} ${h}:${min}`;
};

const getActivityList = () => {
  const userId = uni.getStorageSync('userInfo')?.id;
  if (!userId) return;
  request({
    url: '/admin/api/activity/user/signup/list',
    method: 'GET',
    data: { user_id: userId }
  }).then(res => {
    if (res.data && res.data.code === 0) {
      activityList.value = res.data.data;
    }
  });
};

const isActivityOngoing = (startTime: string, endTime: string) => {
  const now = new Date();
  const start = new Date(startTime.replace(/-/g, '/'));
  const end = new Date(endTime.replace(/-/g, '/'));
  return now >= start && now <= end;
};

const canCancel = (startTime: string) => {
  const now = new Date();
  const start = new Date(startTime.replace(/-/g, '/'));
  const fourHoursBeforeStart = new Date(start.getTime() - 4 * 60 * 60 * 1000);
  return now < fourHoursBeforeStart;
};

const handleCheckin = (item: any) => {
  const userId = uni.getStorageSync('userInfo')?.id;
  if (!userId) return;
  uni.scanCode({
    success: () => {
      request({
        url: '/admin/api/activity/signup/checkin',
        method: 'POST',
        data: {
          user_id: userId,
          activity_id: item.activity_id
        }
      }).then(res => {
        if (res.data && res.data.code === 0) {
          uni.showToast({
            title: '签到成功',
            icon: 'success'
          });
          getActivityList();
        } else {
          uni.showToast({
            title: res.data?.msg || '签到失败',
            icon: 'none'
          });
        }
      });
    }
  });
};

const handleCancel = (item: any) => {
  uni.showModal({
    title: '提示',
    content: '确定要取消报名吗？',
    success: (res) => {
      if (res.confirm) {
        const userId = uni.getStorageSync('userInfo')?.id;
        if (!userId) return;
        request({
          url: '/admin/api/activity/signup/cancel',
          method: 'POST',
          data: {
            user_id: userId,
            activity_id: item.activity_id
          }
        }).then(res => {
          if (res.data && res.data.code === 0) {
            uni.showToast({
              title: '取消报名成功',
              icon: 'success'
            });
            getActivityList();
          } else {
            uni.showToast({
              title: res.data?.msg || '取消报名失败',
              icon: 'none'
            });
          }
        });
      }
    }
  });
};

const getStatusClass = (status: string) => {
  switch (status) {
    case '已报名': return 'status-pending';
    case '已取消': return 'status-cancelled';
    case '已参加': return 'status-completed';
    case '已逾期': return 'status-overdue';
    default: return '';
  }
};

onMounted(() => {
  getActivityList();
});
</script>

<style>
.container {
  min-height: 100vh;
  background: linear-gradient(135deg, #e3f2fd 0%, #f5f7fa 100%);
  padding: 30rpx;
}
.header {
  text-align: center;
  margin-bottom: 30rpx;
}
.title {
  font-size: 36rpx;
  font-weight: bold;
  color: #1976D2;
}
.activity-list {
  width: 100%;
}
.activity-card {
  background: #fff;
  border-radius: 16rpx;
  box-shadow: 0 4rpx 16rpx rgba(0, 0, 0, 0.1);
  margin-bottom: 30rpx;
  overflow: hidden;
}
.activity-image {
  width: 100%;
  height: 200rpx;
  object-fit: cover;
}
.activity-info {
  padding: 20rpx;
}
.activity-title {
  font-size: 32rpx;
  font-weight: bold;
  color: #333;
  margin-bottom: 10rpx;
}
.activity-time, .activity-location, .activity-points {
  font-size: 24rpx;
  color: #666;
  margin-bottom: 8rpx;
}
.activity-status {
  font-size: 24rpx;
  font-weight: bold;
  margin-top: 10rpx;
}
.status-pending {
  color: #FFA000;
}
.status-cancelled {
  color: #F44336;
}
.status-completed {
  color: #4CAF50;
}
.status-overdue {
  color: #9E9E9E;
}
.activity-actions {
  display: flex;
  justify-content: space-between;
  padding: 20rpx;
  border-top: 1rpx solid #eee;
}
.action-btn {
  flex: 1;
  margin: 0 10rpx;
  height: 60rpx;
  line-height: 60rpx;
  text-align: center;
  border-radius: 30rpx;
  font-size: 28rpx;
  font-weight: bold;
}
.checkin-btn {
  background: #4CAF50;
  color: #fff;
}
.cancel-btn {
  background: #F44336;
  color: #fff;
}
.no-activity {
  text-align: center;
  color: #999;
  font-size: 28rpx;
  margin-top: 40rpx;
}
</style>